<template>
    <view>
        <view class="search_row">
            <input :value="inpValue" placeholder="请输入您要搜索的商品" @input="handleInput" />
            <button @tap="handleCancel" v-if="isFocus">取消</button>
        </view>
        <view class="search_content">
            <view @tap="onGoodsDetail" :data-gid="item.goods_id" class="search_item" v-for="(item, index) in goods" :key="index">
                {{ item.goods_name }}
            </view>
        </view>
    </view>
</template>

<script>
import { request } from '../../request/index.js';
import regeneratorRuntime from '../../lib/runtime/runtime';
export default {
    data() {
        return {
            goods: [],

            // 取消 按钮 是否显示
            isFocus: false,

            // 输入框的值
            inpValue: '',

            TimeId: -1
        };
    },
    methods: {
        // 输入框的值改变 就会触发的事件
        handleInput(e) {
            // 1 获取输入框的值
            const { value } = e.detail;
            // 2 检测合法性
            if (!value.trim()) {
                this.setData({
                    goods: [],
                    isFocus: false
                });
                // 值不合法
                return;
            }
            // 3 准备发送请求获取数据
            this.setData({
                isFocus: true
            });
            clearTimeout(this.TimeId);
            this.TimeId = setTimeout(() => {
                this.qsearch(value);
            }, 1000);
        },

        // 发送请求获取搜索建议 数据
        async qsearch(query) {
            const res = await request({
                url: '/goods/qsearch',
                data: {
                    query
                }
            });
            console.log(res);
            this.setData({
                goods: res
            });
        },

        // 点击 取消按钮
        handleCancel() {
            this.setData({
                inpValue: '',
                isFocus: false,
                goods: []
            });
        },

        onGoodsDetail: function (event) {
            const gid = event.currentTarget.dataset.gid;
            console.log('onGoodsDetail gid:', gid);
            uni.navigateTo({
                url: `/pages/goodsdetails/goodsdetails?gid=${gid}`
            });
        }
    }
};
</script>
<style>
page {
    background-color: #dedede;
    padding: 20rpx;
}
.search_row {
    height: 60rpx;
    display: flex;
}
.search_row input {
    background-color: #fff;
    flex: 1;
    height: 100%;
    padding-left: 30rpx;
}
.search_row button {
    width: 110rpx;
    height: 100%;
    padding: 0;
    margin: 0 10rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 26rpx;
}
.search_content {
    margin-top: 30rpx;
}
.search_content .search_item {
    background-color: #fff;
    font-size: 26rpx;
    padding: 15rpx 10rpx;
    border-bottom: 1rpx solid #ccc;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
</style>
